import { Card, Table, Image } from 'antd';
import { fetchWallpaperListAPI } from '@/apis/wallpaper'
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import './index.scss'

import type { Wallpaper, WallpaperParams } from '@/apis/wallpaper';

const Wallpaper = () => {
  const { t } = useTranslation()
  const columns = [{
    title: t('wallpaper image'),
    dataIndex: 'downloadImageUrl',
    key: 'downloadImageUrl',
    render: (imgUrl: string) => {
      return <Image height={60} src={imgUrl + '?imageView2/0/h/60'} preview={{
        src: imgUrl
      }} />
    }
  }, {
    title: t('wallpaper download count'),
    dataIndex: 'downloadCount',
    key: 'downloadCount'
  }, {
    title: t('wallpaper create time'),
    dataIndex: 'createTime',
    render: (createTime: string) => {
      return createTime.replace('T', ' ')
    }
  }, {
    title: t('wallpaper update time'),
    dataIndex: 'updateTime',
    render: (updateTime: string) => {
      if (updateTime) {
        return updateTime.replace('T', ' ')
      } else {
        return ''
      }
    }
  }, {
    title: t('wallpaper category'),
    dataIndex: 'categoryId',
  }, {
    title: t('wallpaper search words'),
    dataIndex: 'searchKeywords',
  }]
  const [reqData, setReqData] = useState<WallpaperParams>({
    pageNo: 1,
    pageSize: 10,
    categoryId: ''
  })
  const [dataSource, setDataSource] = useState<Wallpaper[]>([]); // dataSource
  const [count, setCount] = useState(0)
  useEffect(() => {
    const getList = async () => {
      const res = await fetchWallpaperListAPI(reqData)
      console.log(res)
      if (res.code == 0) {
        setDataSource(res.data.list)
        setCount(res.data.total)
      }
    }
    getList()
  }, [reqData])

  // 页码变化
  const onPageChange = (pageNo: number) => {
    // 修改参数依赖项，引发数据的重新获取列表渲染
    setReqData({
      ...reqData,
      pageNo
    })
  }

  // 分页大小改变
  const onPageSizeChange = (current: number, pageSize: number) => {
    setReqData({
      ...reqData,
      pageSize
    })
  }

  return (
    <div>
      <Card className='search'>
        这是筛选区域
      </Card>

      <Card>
        <Table dataSource={dataSource} rowKey={(row) => row.id} columns={columns}
          bordered
          pagination={{
            total: count,
            pageSize: reqData.pageSize,
            onChange: onPageChange,
            onShowSizeChange: onPageSizeChange
          }} />
      </Card>
    </div>
  )
}

export default Wallpaper